package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        // 将字符串转为Long数组
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        // 获取套餐审核对象
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        // 获取流程信息对象
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(carPackageAudit.getBpmnInfoId());
        List<String> highLightedActivities;

        // 审核中的流程图才需要高亮
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            highLightedActivities = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        } else {
            highLightedActivities = new ArrayList<>();
        }
        // 创建默认流程图生成器对象
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        // 获取bpmn模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        return generator.generateDiagram(bpmnModel, highLightedActivities, Collections.EMPTY_LIST,
                "宋体", "宋体", "宋体");
    }

    @Override
    public void cancelApply(Long id) {
        // 将套餐审核状态修改为审核撤销
        CarPackageAudit audit = this.get(id);
        carPackageAuditMapper.changeAuditStatus(id, CarPackageAudit.STATUS_CANCEL);
        // 删除流程实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "撤销审核");
        // 将养修服务单项审核状态修改为初始化
        serviceItemMapper.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        // 通过id获取套餐审核对象
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        // 获取服务单项
        ServiceItem serviceItem = serviceItemMapper.selectById(audit.getServiceItemId());

        // 合理性校验
        // 处于审核中的套餐才能进行审核
        if (!ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("非法操作！");
        }
        // 当前登录用户是审核对象的审核人才能进行审核
        if (!ShiroUtils.getUserId().equals(audit.getAuditorId())) {
            throw new BusinessException("非法操作！");
        }

        // 根据审核意见（通过/拒绝），将审核人审核信息记录到info中
        String userName = ShiroUtils.getUser().getUserName();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            info = audit.getInfo() + "<br/> " + userName + "【同意】，批注意见：" + info;
        } else {
            info = audit.getInfo() + "<br/> " + userName + "【拒绝】，批注意见：" + info;
        }
        audit.setInfo(info);

        // 根据套餐审核对象获取当前任务
        String instanceId = audit.getInstanceId();
        Task currentTask = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        // 给任务添加流程变量
        String taskId = currentTask.getId();
        taskService.setVariable(taskId, "auditStatus", auditStatus);
        taskService.addComment(taskId, instanceId, info);
        // 完成任务
        taskService.complete(taskId);

        // 根据流程实例ID查询下一个任务
        Task nextTask = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();

        // 判断审核通过还是拒绝
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            if (nextTask != null) {     // 存在下个任务
                // 获取任务处理人并封装进audit中
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            } else {    // 没有下个任务
                audit.setAuditorId(null);
                audit.setAuditTime(new Date());
                // 服务单项的审核状态修改为审核通过
                serviceItemMapper.changeAuditStatus(serviceItem.getId(), ServiceItem.AUDITSTATUS_APPROVED);
                // 审核对象的状态修改为通过
                carPackageAuditMapper.changeAuditStatus(id, CarPackageAudit.STATUS_PASS);
            }
        } else {
            // 如果是拒绝
            // 审核对象的审核人id设为null
            audit.setAuditorId(null);
            audit.setAuditTime(new Date());
            // 审核对象的状态修改为拒绝
            carPackageAuditMapper.changeAuditStatus(id, CarPackageAudit.STATUS_REJECT);
            // 服务单项的审核状态修改为重新调整
            serviceItemMapper.changeAuditStatus(serviceItem.getId(), ServiceItem.AUDITSTATUS_REPLY);
        }
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }
}
